#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef double db;

#define in read()
#define pii pair<int,int>
#define fi first
#define se second
#define FILE(x) freopen(x".in","r",stdin);\
	freopen(x".out","w",stdout);
#define pb push_back

int read(){
	int x = 0,sgn = 1;char ch = getchar();
	for(;!isdigit(ch);ch = getchar()) if(ch == '-') sgn = -1;
	for(;isdigit(ch);ch = getchar()) x = (x<<1)+(x<<3)+(ch^48);
	return x*sgn;
}

const int MAXN = 1e5+10;

int ch[MAXN][26],ans[MAXN],dfn[MAXN],ddfn[MAXN],tr[MAXN<<1],CH[MAXN][26],tot = 1,ls = -1,fail[MAXN],tim,ql[MAXN],qr[MAXN],en[MAXN],n,nf[MAXN],fa[MAXN];
char al[MAXN];

struct query{int x,y,id;}q[MAXN];

vector<int> G[MAXN];

void add(int x,int y){for(;x<=tot;x+=x&-x) tr[x] += y;}

int getsum(int x){int res = 0;for(;x;x-=x&-x) res+=tr[x];return res;}

void getfail(){
	queue<int> q; for(int i = 0;i < 26;i++) ch[0][i] = 1; q.push(1);
	while(q.size()){
		int x = q.front();q.pop(); int FAIL = fail[x];
		for(int i = 0;i < 26;i++){
			if(!ch[x][i]) ch[x][i] = ch[FAIL][i];
			else fail[ch[x][i]] = ch[FAIL][i],q.push(ch[x][i]);
		}
	}
}

void dfs(int x){
	dfn[x] = ++tim;
	for(int y : G[x]) dfs(y);
	ddfn[x] = tim;
}

void DFS(int x){
	add(dfn[x],1);
	if(en[x]){
		for(int i = ql[en[x]];i <= qr[en[x]];i++){
			ans[q[i].id] = getsum(ddfn[nf[q[i].x]]) - getsum(dfn[nf[q[i].x]]-1);
		}
	}
	for(int i = 0;i < 26;i++) if(CH[x][i]) DFS(CH[x][i]);
	add(dfn[x],-1);
}

int main (){
#ifndef ONLINE_JUDGE
	freopen("1.in","r",stdin);
#endif
	scanf("%s",al); int m = strlen(al); int now = 1;
	for(int i = 0;i < m;i++){
		if(al[i] == 'B') now = fa[now];
		else if(al[i] == 'P') en[now] = ++n,nf[n] = now;
		else {
			if(!ch[now][al[i]-'a']) ch[now][al[i]-'a'] = ++tot;
			fa[ch[now][al[i]-'a']] = now; now = ch[now][al[i]-'a']; 
		}
	} m = in;
	for(int i = 1;i <= m;i++) q[i].x = in,q[i].y = in,q[i].id = i;
	sort(q+1,q+m+1,[](query a,query b){
			return a.y < b.y;
		});
	memcpy(CH,ch,sizeof(ch));
	getfail();
	for(int i = 2;i <= tot;i++) G[fail[i]].pb(i);
	dfs(1);
	for(int i = 1,p = 1,pos = 1;i <= n;i++,p = pos){
		ql[i] = p; pos = p; while(q[pos].y == i) pos++; qr[i] = pos - 1;
	}
	DFS(1);
	for(int i = 1;i <= m;i++) printf("%d\n",ans[i]);
	return 0;
}
